import { observable, action, autorun, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import { WeaForm, WeaTableNew } from 'comsMobx'
import { Modal } from 'antd'
import { message, Button } from "antd";
import * as Apis from '../../apis/info';
import { ListStore } from '../listStore';
import _ from "lodash";
import ResponseData from './data/responseData';
import { Text } from '../../components/util/text';
const text = new Text();

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
export default class composingStore extends ListStore {

    @observable responseData = new ResponseData();
    @observable title1 = "";
    @observable title2 = "";
    @observable options = [];
    @observable columns = [];
    @observable datas = [];
    @observable _datas = [];                  //用于点击修改的弹窗中  临时保存数据
    datasTemp = [];     //用于成文中：修改后点击重新生成更新可编辑列表的数据
    @observable form = new WeaForm();
    @observable buttonVisible = false;        //追加，删除和修改三个按钮的disabled状态
    @observable canDraggle = true;            //可编辑列表是否可以拖拽
    @observable selectKey = "all";            //选择所属子栏目下拉框默认选择值
    @observable selectedRowKeys = [];         //选中项受控
    @observable _selectedRowKeys = [];

    @observable editTableStore = new TableStore();   //修改栏目选择弹出框中tableStore
    @observable periodsTableStore = new TableStore();    //查看历史期数tableStore
    @observable shareListTableStore = new TableStore();    //授权列表tableStore

    @observable upForm = new WeaForm();         //调整期数弹出框updatePeriodsForm
    @observable upCondition = [];               //调整期数弹出框updatePeriodsCondition

    ids = [];
    j_type = "";            //刊型id
    journalId = "";         //期刊id
    editPeriods = "";       //手动调整的期数
    isSpecialReport = false;        //判断该期刊是否是专报，专报只显示正文，不显示明细tab页
    isReload = false;           //判断当前操作是否重新生成，(重新生成保存时传入给空间传入E9Edit)
    @observable selectTabKey = "composing";    //页签默认选中全部类型
    @observable tabs = [{ key: "composing", title: text.COMPOSING }];
    @observable status = {
        loading: false,
        visible: false,                      //修改栏目选择弹出框
        _visible: false,                      //正文中修改按钮批量修改栏目
        upVisible: false,                    //调整期数弹出框
        sureVisible: false,
        shareVisible: false                   //已发布期刊中授权弹出框
    }

    //成文相关
    @observable doctemplate;                //模板id
    @observable docid;                      //公文id
    @observable versionId;                      //公文id
    @observable docstatus;                     //状态
    @observable columnData = {};                 //栏目信息  含栏目内的待编信息
    @observable siftData = {};                   //全部待编信息  this.siftData  跟window.siftData存在区别  this.siftData不会清除已经删除的数据  而windowsiftData.siftData中只有当前文中的内容
    @observable src = "";
    @observable showEdit = false;
    @observable showModel = false;
    @observable showEdition = false;
    @observable showType = "";
    @observable office2015 = false;
    @observable hideObject = false;       //隐藏iframe

    isSiftRole = false;       //是否是采编角色
    pathId;                   //当前路径

    @observable isRight = false;        //判断是否有权限
    @observable loadingSpin = true;     //全局loading

    constructor(props) {
        super(props);
    }
    setState = (params = {}) => {
        Object.keys(params).forEach(o => {
            this.status[o] = params[o];
        })
        return this;
    }
    //得到待处理list
    @action
    initList = (params = {}) => {
        this.isSpecialReport = params.isSpecialReport;
        this.showType = params.type;
        //this.journalId = params.id;
        this.ids = params.ids;
        this.status.loading = true;
        let newParams = { ...params, ids: this.ids };
        this.j_type = params.j_type;       //选择刊型排版时从url中获取刊型id
        if (params.id)
            this.journalId = params.id;
        this.loadingSpin = true;
        Apis.getComposingCondition(newParams).then(data => {
            if (data.api_status == '1') {
                this.loadingSpin = false;
                this.isRight = data.isRight;
                if (!this.isRight) {
                    return;
                }
                this.office2015 = data.office2015;
                this.j_type = data.j_type;
                this.selectKey = 'all';  //全部显示
                this.canDraggle = data.canDraggle;
                this.options = data.options;
                this.title1 = data.tableTitle;
                this.title2 = data.formTitle;
                this.columns = data.columns;
                this.datas = toJS(data.datas);
                this._datas = toJS(data.datas);
                this.datasTemp = toJS(data.datas);
                this.buttonVisible = false;
                this.responseData.rightMenus = data.rightMenus;
                this.responseData.condition = data.infoConditionGroup;
                this.isSiftRole = data.isSiftRole;
                this.pathId = data.pathid;
                //成文相关
                this.doctemplate = data.doctemplate;
                this.docid = data.docid;
                this.docstatus = data.docstatus;
                this.columnData = data.columnData;
                this.siftData = data.siftData;
                this.versionId = data.versionId;
                window.docid = toJS(this.docid);
                window.doctemplate = this.doctemplate;
                window.columnData = toJS(this.columnData);
                window.columnDataTemp = toJS(this.columnData);      //重新生成时用该数据重新生成信息
                window.siftDataTemp = toJS(this.siftData);          //重新生成时待编信息列表
                window.siftData = toJS(this.siftData);
                window.periods = data.periods;
                if (this.docstatus > 0) {
                    //这里还需要添加 成文页面的操作权限
                    //this.tabs.push({ key: "edition", title: "正文" })
                    //this.tabs = [{ key: "edition", title: text.CONTENT }, { key: "composing", title: text.DETAIL }];
                    if (this.isSpecialReport == 'true') {
                        this.tabs = [{ key: "edition", title: text.CONTENT }];
                    } else {
                        this.tabs = [{ key: "edition", title: text.CONTENT }, { key: "composing", title: text.DETAIL }];
                    }
                    this.selectTabKey = "edition";
                    this.showEdition = true;
                }
                //已发布的期刊展示授权列表信息
                if (this.docstatus == 5) {
                    this.tabs.push({
                        key: "shareList",
                        title: '共享'
                    });
                }
                //this.showType = newParams.type;
                //this.getSrc();
                //
                if (newParams.type === 'show' || newParams.type === 'edit') {
                    this.form.resetForm();
                    this.form = new WeaForm();
                    this.form.setCondition(data.infoConditionGroup);
                    if (newParams.type === 'show') {
                        this.buttonVisible = true;
                    }
                } else {
                    this.form && !this.form.isFormInit && this.form.initFormFields(this.responseData.condition);
                }
                this.status.loading = false;
                if (this.docstatus > 0 && data.isSource) {
                    // if (!this.isIE()) {
                    //     this.getSrc();
                    // 	return;
                    // }
                    let _this = this;
                    _this.hideObject = true;
                    //快捷筛选打开期刊时不需要提示信息
                    if (newParams.isQuickSift) {
                        _this.showType = 'edit';
                        _this.changeURL({ journalId: _this.journalId, type: 'edit' })
                        _this.status.sureVisible = true;
                        //_this.getSrc();
                        return;
                    }
                    Modal.confirm({
                        title: '提示信息',
                        content: '有快捷筛选的上报信息未进行排版，是否编辑？',
                        onOk() {
                            _this.showType = 'edit';
                            _this.changeURL({ journalId: _this.journalId, type: 'edit' })
                            _this.status.sureVisible = true;
                            //_this.getSrc();
                        },
                        onCancel() {
                            _this.hideObject = false;
                            _this.getSrc();
                        },
                    })
                } else {
                    this.getSrc();
                }
            } else {
                message.error(data.api_errormsg);
            }
        })
    }

    @action
    saveComposing = (params = {}) => {
        //可编辑列表必填校验 tableEdit为可编辑列表组件ref定义的
        let r = this.tableEdit.refs.edit.doRequiredCheck();
        if (r.pass) {
            let newParams = { ...params, periods: this.editPeriods };
            let ids = [];
            this.datas.map(m => {
                ids.push(m.id);
            });
            if (params.type == '0') {   //保存
                Apis.saveInfoJournal(newParams).then(result => {
                    if (result.api_status == '1') {
                        if (!result.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
                        this.journalId = result.id;
                        message.success(text.SAVESUCCESS);
                        //传给后台每条记录的id，进行展示
                        this.initList({ ids: ids.join(","), type: 'show', id: this.journalId });
                        this.editPeriods = "";
                        // let url = '/#/info/composing?id=' + this.journalId + '&type=show';
                        // window.location.href = url;
                        this.changeURL({ journalId: this.journalId, type: 'show' })
                    } else {
                        message.error(data.api_errormsg);
                    }
                })
            }
            if (params.type == '1') {   //编辑保存
                Apis.updateInfoJournal(newParams).then(result => {
                    if (result.api_status == '1') {
                        if (!result.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
                        message.success(text.SAVESUCCESS);
                        this.initList({ ids: ids.join(","), type: 'show', id: this.journalId });
                        this.editPeriods = "";
                        // let url = '/#/info/composing?id=' + this.journalId + '&type=show';
                        // window.location.href = url;
                        this.changeURL({ journalId: this.journalId, type: 'show' })
                    } else {
                        message.error(data.api_errormsg);
                    }
                })
            }
        }
    }

    @action
    saveForm = () => {
        let formParams = this.form.getFormParams();
        let params = { ...formParams };
        this.form.validateForm().then(f => {
            if (f.isValid) {
                Apis.updateInfoSifting(params).then(result => {
                    if (result.api_status == '1') {
                        if (!result.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
                        message.success(text.SAVESUCCESS);
                        let ids = [];
                        this.datas.map(m => {
                            ids.push(m.id);
                        });
                        Apis.getComposingCondition({ ids: ids }).then(data => {
                            this.datas = data.datas;
                        })
                    } else {
                        message.error(data.api_errormsg);
                    }
                })
            } else {
                f.showErrors();
            }
        });
    }

    @action
    getForm = (params = {}) => {
        let newParams = { ...params };
        Apis.getComposingCondition(newParams).then(data => {
            if (data.api_status == '1') {
                this.form.resetForm();
                this.form = new WeaForm();
                this.form.setCondition(data.infoConditionGroup);
            } else {
                message.error(data.api_errormsg);
            }

        })
    }

    changeURL = (params = {}) => {
        //let url = '/#/info/composing?id=' + params.journalId + '&type=' + params.type;
        let url = '/spa/info/static/index.html#/main/info/composing?id=' + params.journalId + '&type=' + params.type;
        window.location.href = url;
    }

    //选择所属子栏目下拉框改变
    @action
    selectChange = (v) => {
        this.selectKey = v;
    }

    //初始化批量修改栏目弹出框
    @action
    initEditDialog = (params = {}) => {
        let newParams = { ...params };
        Apis.getJ_ColumnModalCondition(newParams).then(data => {
            if (data.api_status == '1') {
                this.editTableStore.getDatas(data.sessionkey, 1);
            } else {
                message.error(data.api_errormsg);
            }

        })
    }
    @action
    doEdit = (params = {}) => {
        this.setState({ visible: false });
    }

    //初始化调整期数dialog
    @action
    initUpDialog = (params = {}) => {
        this.upCondition = [];
        let newParams = { ...params };
        Apis.getAdjustPeriodsCondition(newParams).then(data => {
            if (data.api_status == '1') {
                this.upCondition = data.infoConditionGroup;
                this.upForm = new WeaForm();
                this.upForm && !this.upForm.isFormInit && this.upForm.initFormFields(this.upCondition);
            } else {
                message.error(data.api_errormsg);
            }

        });
    }

    //检查调整的期数是否有效
    checkPeriods = (params = {}) => {
        let formParams = this.upForm.getFormParams();
        let newParams = { ...formParams, j_type: this.j_type };
        Apis.checkInfoPeriods(newParams).then(data => {
            if (data.api_status == '1') {
                if (data.result == true) {
                    this.title1 = data.tableTitle;
                    this.editPeriods = newParams.periods;
                    this.setState({ upVisible: false });
                    this.hideObject = false;
                    if(this.selectTabKey == 'edition'){
                        this.showOffice();
                    }
                    window.periods = newParams.periods;
                    window.hideIframe.changePeriods();
                } else {
                    message.error(text.TIP10);
                }
            } else {
                message.error(data.api_errormsg);
            }

        });
    }

    @action
    getHistoricalPeriodsList = (params = {}) => {
        if (params.length == "1") {
            let newParams = { ...params, 'j_type': this.j_type };
            Apis.getHistoricalPeriodsList(newParams).then(data => {
                if (data.api_status == '1') {
                    this.periodsTableStore.getDatas(data.sessionkey, 1);
                } else {
                    message.error(data.api_errormsg);
                }

            })
        }
    }

    //设置选中按钮
    @action
    changeTab = (key) => {
        this.selectTabKey = key;
        if(this.selectTabKey == 'edition'){
            this.showOffice();
        }else{
            this.hideOffice();
        }
        if (key == 'shareList') {
            let params = { 'id': this.journalId };
            Apis.getShareList(params).then(data => {
                if (data.api_status == '1') {
                    this.shareListTableStore.getDatas(data.sessionkey, 1);
                } else {
                    message.error(data.api_errormsg);
                }
            })
        }
    }
    showOffice = () => {
        if(this.office2015){
            window.hideIframe.showIwebOffice();//显示插件
        }
    }
    hideOffice = () => {
        if(this.office2015){
            window.hideIframe.hideIwebOffice();//隐藏插件
        }
    }
    
    getRightMenu = () => {
        let btnArr = [];
        if (this.selectTabKey == 'shareList' && this.isSiftRole == true) {
            btnArr.push({
                key: 'BTN_AUTHORIZATION',
                icon: <i className='icon-coms-New-Flow' />,
                content: '添加',
                onClick: key => {
                    this.buttonClick("BTN_AUTHORIZATION");
                },
            })
            btnArr.push({
                key: 'BTN_DELETE',
                icon: <i className='icon-coms-delete' />,
                content: text.DELETE,
                disabled: this.shareListTableStore.selectedRowKeys.length === 0,
                onClick: key => {
                    this.buttonClick("BTN_DELETE");
                },
            })
        }
        return btnArr;
    }


    /**
   * 上方按钮
   */
    getTopButton = () => {
        let btnArr = [];
        if (this.selectTabKey == 'composing') {
            //点击成文按钮之后排版页签内不展示按钮
            if (this.docstatus == 0 && this.tabs.length == 1) {
                if (this.showType == 'edit') {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qqa9vs@BTN_ADJUST`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.buttonClick("BTN_ADJUST");
                            }}>
                            {text.UPDATEPERIODS}
                        </Button>
                    );
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fq017g@BTN_EDIT_SAVE`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.buttonClick("BTN_EDIT_SAVE");
                            }}>
                            {text.SAVE}
                        </Button>
                    );
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mifxvq@chengwen}`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                //alert("this.siftData" + JSON.stringify(this.siftData));
                                //alert("window.siftData" + JSON.stringify(window.siftData));
                                if (this.isIE()) {
                                    this.chengwen();
                                } else {
                                    message.error(text.ISIE);
                                }
                            }}>
                            {text.EDITION}
                        </Button>
                    );
                } else if (this.showType == 'show') {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@07xpzd@BTN_EDIT`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.buttonClick("BTN_EDIT");
                            }}>
                            {text.EDIT}
                        </Button>
                    );
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@z7vcya@BTN_EDIT_ARTICLE`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                if (this.isIE()) {
                                    this.buttonClick("BTN_EDIT_ARTICLE");
                                } else {
                                    message.error(text.ISIE);
                                }
                            }}>
                            {text.EDITION}
                        </Button>
                    );
                } else {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@llfyh9@BTN_ADJUST`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.buttonClick("BTN_ADJUST");
                            }}>
                            {text.UPDATEPERIODS}
                        </Button>
                    );
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2sm4kr@BTN_SAVE`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.buttonClick("BTN_SAVE");
                            }}>
                            {text.SAVE}
                        </Button>
                    );
                }
            }
        } else if (this.selectTabKey == 'edition' && this.isIE()) {
            if (this.docstatus < 5 && this.docstatus != 3) {
                if (this.showType === "edit") {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c7t9uw@updateInfoJournal`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                let params = { tableJson: JSON.stringify(this.datas), id: this.journalId, type: '1', title: this.title1, periods: this.editPeriods }
                                Apis.updateInfoJournal(params).then(result => {
                                    if (result.api_status == '1') {
                                        if (!result.isRight) {
                                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                            return;
                                        }
                                        message.success(text.SAVESUCCESS);
                                        this.editPeriods = "";
                                        this.showType = 'show';
                                        this.changeURL({ journalId: this.journalId, type: 'show' });
                                        this.saveDoc();
                                    } else {
                                        message.error(data.api_errormsg);
                                    }
                                })
                            }}>
                            {text.SAVE}
                        </Button>
                    );
                    //专报生成的期刊不展示修改和重新生成按钮
                    if (this.isSpecialReport != 'true') {
                        btnArr.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ktcu81@BTN_EDITION`} style={{ marginLeft: "10px" }} type={"primary"}
                                onClick={() => {
                                    this.buttonClick("BTN_EDITION");
                                }}>
                                {text.UPDATE}
                            </Button>
                        );

                        btnArr.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@z4be8n@BTN_RELOAD`} style={{ marginLeft: "10px" }} type={"primary"}
                                onClick={() => {
                                    this.buttonClick("BTN_RELOAD");
                                }}>
                                {text.RELOAD}
                            </Button>
                        );
                    }
                    if (this.docstatus < 3) {
                        btnArr.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ypf87d@BTN_ADJUST`} style={{ marginLeft: "10px" }} type={"primary"}
                                onClick={() => {
                                    this.buttonClick("BTN_ADJUST");
                                }}>
                                {text.UPDATEPERIODS}
                            </Button>
                        );
                    }
                } else if (this.showType == 'show') {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j4s2it@changeURL`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                this.showType = 'edit';
                                // let url = '/#/info/composing?id=' + this.journalId + '&type=edit';
                                // window.location.href = url;
                                this.changeURL({ journalId: this.journalId, type: 'edit' })
                                this.getSrc();
                            }}>
                            {text.EDIT}
                        </Button>
                    );

                    //if (this.docstatus < 3) {
                    btnArr.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lj43m5@submitInfoJournal`} style={{ marginLeft: "10px" }} type={"primary"}
                            onClick={() => {
                                Apis.submitInfoJournal({ id: this.journalId }).then(data => {
                                    if (data.api_status == '1') {
                                        if (!data.isRight) {
                                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                            return;
                                        }
                                        message.success(text.SAVESUCCESS);
                                        window.location.reload();
                                    } else {
                                        message.error(text.SAVEFAIl);
                                    }
                                })
                            }}>
                            {text.SUBMIT}
                        </Button>
                    );
                    //}
                }
            }
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5tyoq9@BTN_SWITCH`} style={{ marginLeft: "10px" }} type={"primary"}
                    onClick={() => {
                        this.buttonClick("BTN_SWITCH");
                    }}>
                    {text.CHANGEHEAD}
                </Button>
            );
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1du764@BTN_DOWNLOADN`} style={{ marginLeft: "10px" }} type={"primary"}
                    onClick={() => {
                        this.buttonClick("BTN_DOWNLOADN");
                    }}>
                    {text.DOWNLOADLOCAL}
                </Button>
            );
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xo5o18@BTN_PTINT`} style={{ marginLeft: "10px" }} type={"primary"}
                    onClick={() => {
                        this.buttonClick("BTN_PTINT");
                    }}>
                    {text.PRINTING}
                </Button>
            );
        } else if (this.selectTabKey == 'shareList' && this.isSiftRole == true) {
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@o8jh29@BTN_AUTHORIZATION`} style={{ marginLeft: "10px" }} type={"primary"}
                    onClick={() => {
                        this.buttonClick("BTN_AUTHORIZATION");
                    }}>
                    {'添加'}
                </Button>
            );
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mt7kic@BTN_DELETE`} style={{ marginLeft: "10px" }} type={"primary"}
                    disabled={this.shareListTableStore.selectedRowKeys.length === 0}
                    onClick={() => {
                        this.buttonClick("BTN_DELETE");
                    }}>
                    {text.DELETE}
                </Button>
            );
        }
        return btnArr;
    }

    isIE = () => { //ie?
        if(this.office2015)
            return true;
        if (!!window.ActiveXObject || "ActiveXObject" in window)
            return true;
        else
            return false;
    }

    buttonClick(key) {
        if (key == 'BTN_ADJUST') {      //调整期数
            this.initUpDialog();
            this.hideObject = true;
            if(this.selectTabKey == 'edition'){
                this.hideOffice();
            }
            this.setState({ upVisible: true });
        } else if (key == 'BTN_SAVE') {        //保存
            let params = JSON.stringify(this.datas);
            this.saveComposing({ tableJson: params, title: this.title1, j_type: this.j_type, type: '0' });
        } else if (key == 'BTN_EDIT') {        //编辑
            let ids = [];
            this.datas.map(m => {
                ids.push(m.id);
            });
            this.initList({ ids: ids.join(","), type: 'edit', id: this.journalId });
            this.changeURL({ journalId: this.journalId, type: 'edit' })
        } else if (key == 'BTN_EDIT_SAVE') {       //编辑保存
            let params = JSON.stringify(this.datas);
            this.saveComposing({ tableJson: params, id: this.journalId, type: '1', title: this.title1 });
            // if (this.docstatus > 0)
            //     this.saveDoc();
        } else if (key == 'BTN_EDIT_ARTICLE') {        //成文
            Apis.checkRightByJournal({ id: this.journalId }).then(data => {
                if (data.api_status == 1) {
                    if (!data.isRight) {
                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                        return;
                    }
                    if (this.tabs.length == 1) {
                        this.tabs.push({ key: "edition", title: text.CONTENT });
                    }
                    this.selectTabKey = "edition";
                    this.showEdition = true;
                    this.showType = 'edit';
                    // let url = '/#/info/composing?id=' + this.journalId + '&type=edit';
                    // window.location.href = url;
                    this.changeURL({ journalId: this.journalId, type: 'edit' })
                    //this.getSrc();
                } else {
                    message.error(data.msg);
                }
            })
        } else if (key == 'BTN_SUBMIT') {      //成文提交
            let params = JSON.stringify(this.datas);
            this.saveComposing({ tableJson: params, id: this.journalId, type: '1', title: this.title1 });
            //if (this.docstatus > 0)
            this.saveDoc();
        } else if (key === 'BTN_EDITION') {     //修改
            Apis.checkRightByJournal({ id: this.journalId }).then(data => {
                if (data.api_status == 1) {
                    if (!data.isRight) {
                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                        return;
                    }
                    this._datas = _.cloneDeep(toJS(this.datas));
                    this.selectedRowKeys = [];
                    this.showEdit = true;
                    this.hideObject = true;
                    this.hideOffice();
                } else {
                    message.error(data.msg);
                }
            })
        } else if (key === 'BTN_RELOAD') {      //重新生成
            Apis.checkRightByJournal({ id: this.journalId }).then(data => {
                if (data.api_status == 1) {
                    if (!data.isRight) {
                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                        return;
                    }
                    let _this = this;
                    this.hideObject = true;
                    this.hideOffice();
                    Modal.confirm({
                        title: text.DOSURE,
                        content: text.DOSURE2,
                        onOk() {
                            // _this.hideObject = false;
                            // window.hideIframe.changeContent();
                            _this.hideObject = false;
                            //window.hideIframe.contentReload();
                            _this.src = "/spa/info/infoedition/office.html?mTemplate=" + _this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + _this.title1 + "&reload=1";
                            if(_this.office2015){
                                _this.src = "/govern/info/infoOffice2015.jsp?docid="+_this.docid+"&mTemplate=" + _this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + _this.title1 + "&reload=1";
                            }
                            
                            document.getElementById("hideIframe").src = _this.src;
                            _this.isReload = true;
                            _this.datas = _this.datasTemp;
                            _this._datas = _this.datasTemp;
                        },
                        onCancel() { _this.hideObject = false; },
                    })
                } else {
                    message.error(data.msg);
                }
            })
        } else if (key === 'BTN_SWITCH') {
            window.hideIframe.changeRed();
        } else if (key === 'BTN_DOWNLOADN') {
            window.hideIframe.WebSaveLocal();
        } else if (key === 'BTN_PTINT') {
            window.hideIframe.onPrintDoc();
        } else if (key == 'BTN_DELETE') {
            let selectedRowKeys = this.shareListTableStore.selectedRowKeys;
            Apis.delShare({ ids: selectedRowKeys.join(',') }).then(data => {
                if (data.api_status == '1') {
                    if (!data.isRight) {
                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                        return;
                    }
                    message.success(text.DELSUCCESS);
                    this.shareListTableStore.getDatas(this.shareListTableStore.dataKey, this.shareListTableStore.current, this.shareListTableStore.pageSize, this.shareListTableStore.sortParams)
                } else {
                    message.error(data.api_errormsg);
                }

            });
        } else if (key == 'BTN_AUTHORIZATION') {
            this.status.shareVisible = true;
        }
    }
    /**
     * 成文提交
     */
    @action
    saveDoc = (params = {}) => {
        //alert("开始保存文档");
        const docDatas = window.hideIframe.SaveDocument(this.isReload);
        if (docDatas.off_status == 1 && this.journalId) {
            const params = {
                journalId: this.journalId, docid: this.docid || "", docSubject: this.title1, docmain: this.title1, maindoc: -1,
                seccategory: '', isOffice: 1, operate: "submit", docPublishType: 2, doccontent: "", ...docDatas
            };
            Apis.saveDoc(params).then(data => {
                if (data.api_status == '1') {
                    message.success(text.SAVESUCCESS);
                    this.docid = data.docid;
                    this.initList({ type: 'show', id: this.journalId });
                } else {
                    message.error(data.msg);
                }
            })
        } else {
            message.error(text.OPERATEFAIL);
        }
    }

    closeEdit = (flag) => {
        this.hideObject = flag;
        this.showEdit = flag;
        if(flag){
            this.hideOffice();
        }else{
            this.showOffice();
        }
    }

    //得到下拉框的值
    getOptions = () => {
        let btnArr = [];
        this.options && this.options.length > 0 && this.options.map(m => {
            btnArr.push({
                key: m.key,
                showname: m.showname,
                selected: m.selected,
            })

        });
        return btnArr;
    }
    @action
    onChangeEdit = () => {
        this.datas = _.cloneDeep(toJS(this._datas));
        this.hideObject = false;
        this.showOffice();
        this.showEdit = false;
        try {
            var addStr = "";
            var newData = {};
            //获取新增明细的正文 start
            var cd = _.cloneDeep(toJS(this._datas));

            cd.map((obj, index) => {
                var obj = cd[index];
                var id = obj.id;
                if (!this.siftData[id]) {
                    addStr += "," + id;
                }
            });
            //alert("addStr" + addStr);
            if (addStr) {
                Apis.getNewData({ ids: addStr }).then(data => {
                    newData = data.siftData;
                    this.checkDatas(cd, newData);
                })
            } else {
                this.checkDatas(cd, []);
            }
        } catch (e) {
            //console.log(e);
        }
    }

    checkDatas = (cd, newData) => {
        try {
            //处理栏目
            var typeMap = {};
            var typeList = [];
            this.options && this.options.length > 0 && this.options.map(m => {
                if (m.key !== "all") {
                    var obj = {
                        id: m.key,
                        name: m.showname,
                    };
                    typeList.push(obj)
                    typeMap[m.key] = obj;
                }
            });
            var returnStr = "";
            var returnMap = {};
            var returnList = [];

            cd.map((obj, index) => {
                var id = obj.id;
                var typeid = obj.j_column;
                if (typeid) {
                    var dataMap = returnMap[typeid] ? returnMap[typeid] : {};
                    var list = returnMap[typeid] ? dataMap.data : [];
                    if (!returnMap[typeid]) {
                        dataMap.id = typeid;
                        var type = typeMap[typeid].name;
                        dataMap.name = type;
                    }
                    var returnObj = {};
                    if (this.siftData[id]) {
                        returnObj = this.siftData[id];
                    } else {
                        if (newData[id])
                            returnObj = newData[id];
                    }

                    obj.index = list.length;
                    obj.groupIndex = typeid + "-" + list.length;

                    list.push(returnObj);
                    returnStr += "," + id;
                    dataMap.data = list;
                    returnList.push(obj);
                    returnMap[typeid] = dataMap;
                }
            });

            this.siftData = Object.assign(this.siftData, newData);
            window.hideIframe.changeContent({ returnMap, returnList, typeList, returnStr });
        } catch (e) {
        }
    }

    @action
    chengwen = () => {
        Apis.checkRightByJournal({ id: this.journalId }).then(data => {
            if (data.api_status == 1) {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                try {
                    var addStr = "";
                    var newData = {};
                    //获取新增明细的正文 start
                    var cd = _.cloneDeep(toJS(this.datas));

                    cd.map((obj, index) => {
                        var obj = cd[index];
                        var id = obj.id;
                        if (!this.siftData[id]) {
                            addStr += "," + id;
                        }
                    });

                    if (addStr) {
                        Apis.getNewData({ ids: addStr }).then(data => {
                            newData = data.siftData;
                            this.checkData(cd, newData);
                        })
                    } else {
                        this.checkData(cd, []);
                    }
                } catch (e) {
                }
            } else {
                message.error(data.msg);
            }
        })
    }
    checkData = (cd, newData) => {
        try {
            //处理栏目
            var typeMap = {};
            var typeList = [];
            this.options && this.options.length > 0 && this.options.map(m => {
                if (m.key !== "all") {
                    var obj = {
                        id: m.key,
                        name: m.showname,
                    };
                    typeList.push(obj)
                    typeMap[m.key] = obj;
                }
            });
            var returnStr = "";
            var returnMap = {};
            var returnList = [];

            cd.map((obj, index) => {
                var id = obj.id;
                var typeid = obj.j_column;
                if (typeid) {
                    var dataMap = returnMap[typeid] ? returnMap[typeid] : {};
                    var list = returnMap[typeid] ? dataMap.data : [];
                    if (!returnMap[typeid]) {
                        dataMap.id = typeid;
                        var type = typeMap[typeid].name;
                        dataMap.name = type;
                    }
                    var returnObj = {};
                    if (this.siftData[id]) {
                        returnObj = this.siftData[id];
                    } else {
                        if (newData[id])
                            returnObj = newData[id];
                    }

                    obj.index = list.length;
                    obj.groupIndex = typeid + "-" + list.length;

                    list.push(returnObj);
                    returnStr += "," + id;
                    dataMap.data = list;
                    returnList.push(obj);
                    returnMap[typeid] = dataMap;
                }
            });

            this.siftData = Object.assign(this.siftData, newData);
            window.columnData = returnMap;
            if (this.tabs.length == 1) {
                this.tabs.push({ key: "edition", title: text.CONTENT });
            }
            this.selectTabKey = "edition";
            this.showEdition = true;
            this.showType = 'edit';
            // let url = '/#/info/composing?id=' + this.journalId + '&type=edit';
            // window.location.href = url;
            this.changeURL({ journalId: this.journalId, type: 'edit' })
        } catch (e) {
        }
    }

    getSrc = () => {
        var editType = this.showType === 'edit' ? "1" : "0";
        if (this.docstatus > 0) {
            //判断是否是IE浏览器
            if (!this.isIE()) {
                //message.error(text.ISIE);
                this.src = "/spa/document/index.jsp?id=" + this.docid + "&router=1#/main/document/detail";
                if(this.office2015){
                    this.src = "/govern/info/infoOffice2015.jsp?id=" + this.docid + "&router=1#/main/document/detail";
                }
                document.getElementById("hideIframe").src = this.src;
                return;
            }
        }
        this.src = this.docstatus > 0 ? "/spa/info/infoedition/office.html?mRecordID=" + this.versionId + "_" + this.docid + "&mFileType=.doc&mEditType=" + editType + "&mFileName=" + this.title1
            : "/spa/info/infoedition/office.html?mTemplate=" + this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + this.title1;
        if(this.office2015){
            this.src = this.docstatus > 0 ? "/govern/info/infoOffice2015.jsp?docid="+this.docid+"&mRecordID=" + this.versionId + "_" + this.docid + "&mFileType=.doc&mEditType=" + editType + "&mFileName=" + this.title1
            : "/govern/info/infoOffice2015.jsp?mTemplate=" + this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + this.title1;
        }
        if (this.docstatus > 0) {
            document.getElementById("hideIframe").src = this.src;
        }
        //alert(this.src);
        return this.src;
        // var editType = this.showType === 'edit' ? "1" : "0";
        // this.src = this.docstatus > 0 ? "http://localhost:8070/spa/info/infoedition/office.html?mRecordID=" + this.versionId + "_" + this.docid + "&mFileType=.doc&mEditType=" + editType + "&mFileName=正文.doc"
        //      : "http://localhost:8070/spa/info/infoedition/office.html?mTemplate=" + this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=正文.doc";
        // if(this.docstatus > 0) {
        //     document.getElementById("hideIframe").src = this.src;
        // }
        // return this.src;
    }
    //追加
    add = () => {
        this.getSrc();
        if (!this.isIE()) {
            message.error(text.ISIE);
            this.showOffice();
            this.hideObject = false;
            this.setState({ sureVisible: false })
            return;
        }
        setTimeout(() => {
            Apis.updateJournalDeatil({ id: this.journalId }).then(result => {
                if (result.api_status == '1') {
                    this.hideObject = false;
                    this.showOffice();
                    this.setState({ sureVisible: false });
                    // let siftIds = result.siftIds;
                    // for(let i = 0; i < siftIds.length; i++) {
                    //     if(this.siftData[siftIds[i]]) {
                    //         delete this.siftData[siftIds[i]];
                    //     }
                    // }
                    // //{"37":{"data":[{"content":"20190301测试005","id":"548","title":"20190301测试005","typeid":"37","unit":"自定义单位2"}],"id":"37","name":"路径A刊型1栏目1"}}"
                    // window.siftData = this.siftData;
                    // for(let i = 0; i < result.siftData; i++) {
                    //     let columnId = result.siftData.columnId;
                    //     if(window.columnData[columnId]) {
                    //         let data = window.columnData[columnId][data];
                    //         let newData = data.filter(function(item) {　
                    //     　　　　if (item % 2 !== 0) {
                    //     　　　　　　return item;
                    //     　　　　 }
                    //     　　 });
                    //     }
                    // }
                    // let siftData = result.siftData;
                    // for(let i = 0; i < siftData; i++) {
                    //   this._datas.push({
                    //       id: siftData.id,
                    //       j_column: siftData.columnId,
                    //       reportorg: siftData.unit,
                    //       title: siftData.title
                    //   });
                    // }
                    // this.onChangeEdit();
                    //alert("siftDatas" + JSON.stringify(result.siftDatas))
                    window.hideIframe.addContent({ siftDatas: result.siftDatas });
                } else {
                    message.error(data.api_errormsg);
                }
            })
        }, 600);
        
        
    }

    reload = () => {
        this.getSrc();
        if (!this.isIE()) {
            message.error(text.ISIE);
            this.showOffice();
            this.hideObject = false;
            this.setState({ sureVisible: false })
            return;
        }
        setTimeout(() => {
            Apis.updateJournalDeatil({ id: this.journalId }).then(result => {
                if (result.api_status == '1') {
                    this.src = "/spa/info/infoedition/office.html?mTemplate=" + this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + this.title1 + "&reload=1";
                    if(this.office2015){
                        this.src = "/govern/info/infoOffice2015.jsp?docid="+this.docid+"&mTemplate=" + this.doctemplate + "&mFileType=.doc&mEditType=1&mFileName=" + this.title1 + "&reload=1";
                    }
                    document.getElementById("hideIframe").src = this.src;
                    this.isReload = true;
                    this.showOffice();
                    this.hideObject = false;
                    this.setState({ sureVisible: false })
                } else {
                    message.error(data.api_errormsg);
                }
            })
        }, 600);
    }

    ignore = () => {
        this.getSrc();
        if (!this.isIE()) {
            message.error(text.ISIE);
            this.hideObject = false;
            this.showOffice();
            this.setState({ sureVisible: false })
            return;
        }
        setTimeout(() => {
            Apis.updateJournalDeatil({ id: this.journalId }).then(result => {
                if (result.api_status == '1') {
                    message.success('忽略成功');
                    this.hideObject = false;
                    this.showOffice();
                    this.setState({ sureVisible: false })
                } else {
                    message.error(data.api_errormsg);
                }
            })
        }, 600);
    }

	/**
	   * 保存期刊共享权限
	   */
    @action
    addShare = (params) => {
        //添加期刊的非默认共享查看权限   datatype为0   opttype为0
        let newParams = { ...params, pathId: this.pathId || "", datatype: 0, opttype: 0, ids: this.journalId };
        Apis.addShare(newParams).then(data => {
            if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                message.success('添加权限成功');
                let table = this.shareListTableStore;
                table.getDatas(table.dataKey, table.current, table.pageSize, table.sortParams);
            } else {
                message.error(data.api_errormsg);
            }
        });
    }
}